import { notification } from 'antd';
import { Subject } from 'rxjs';

import {
  groupBy, distinctUntilChanged, map, mergeMap
} from 'rxjs/operators';

notification.config({
  placement: 'topRight',
  top: 60,
  duration: 3,
});

const resSubject = new Subject();

resSubject
  .pipe(
    groupBy((data: any) => data.description),
    mergeMap(group$ =>
      group$.pipe(
        map(data => {
          data.timer = new Date().getTime();

          return data;
        }),
        distinctUntilChanged(
          (prev, curr) =>
            new Date().getTime() - prev.timer < 3000 && prev.description === curr.description
        )
      ))
  )
  .subscribe(data => {
    const { message, description, key } = data;
    notification.error({
      message,
      description,
      key,
    });
  });

const asyncErrorHandle = (msg: string) => {
  const message = '出错啦';
  const description = msg || 'Unknown exception';
  const key = `open${Date.now()}`;
  resSubject.next({ message, description, key });
};

export default asyncErrorHandle;
